﻿namespace Cap
{
    internal class Pub<TCapStrategy> : IPub<TCapStrategy>
        where TCapStrategy : class, ICapStrategy
    {
        private readonly ICapStrategy _strategy;

        private readonly List<ICloudEvent> _events = new List<ICloudEvent>();

        public Pub(TCapStrategy strategy)
        {
            _strategy = strategy;
        }

        public async Task PersistAsync(ICloudEvent @event)
        {
            await _strategy.PersistAsync(@event);
            _events.Add(@event);
        }

        public async Task PublishAsync(ICloudEvent @event)
        {
            await _strategy.PublishAsync(@event);
            _events.Remove(@event);
        }

        public async Task DispatchAsync()
        {
            var events = _events.ToArray();
            foreach (var item in events)
            {
                await PublishAsync(item);
            }
        }
    }
}
